package com.xyht.sca_s.student_manage_system.modules.rxRegistrationWelcome.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xyht.sca_s.student_manage_system.common.commonReturn.CommonCodeEnum;
import com.xyht.sca_s.student_manage_system.common.commonReturn.CommonResult;
import com.xyht.sca_s.student_manage_system.common.commonReturn.ExceptionCast;
import com.xyht.sca_s.student_manage_system.common.commonReturn.ResponseResult;
import com.xyht.sca_s.student_manage_system.common.util.ApiModelUtil;
import com.xyht.sca_s.student_manage_system.common.util.ParamCheckUtil;
import com.xyht.sca_s.student_manage_system.common.util.TimeUtil;
import com.xyht.sca_s.student_manage_system.modules.advanceRegistration.entity.RxAdvanceRegistrationOrg;
import com.xyht.sca_s.student_manage_system.modules.advanceRegistration.mapper.RxAdvanceRegistrationOrgMapper;
import com.xyht.sca_s.student_manage_system.modules.common.entity.SmsImportTask;
import com.xyht.sca_s.student_manage_system.modules.common.entity.SmsImportTaskDetail;
import com.xyht.sca_s.student_manage_system.modules.common.mapper.SmsImportTaskDetailMapper;
import com.xyht.sca_s.student_manage_system.modules.common.mapper.SmsImportTaskMapper;
import com.xyht.sca_s.student_manage_system.modules.payment.wxpay.config.WxPayConfig;
import com.xyht.sca_s.student_manage_system.modules.payment.wxpay.entity.WxPayFunctions;
import com.xyht.sca_s.student_manage_system.modules.rxRegistration.entity.*;
import com.xyht.sca_s.student_manage_system.modules.rxRegistration.entity.req.RxRegistrationChargeCategoryRecordDetailReq;
import com.xyht.sca_s.student_manage_system.modules.rxRegistration.entity.req.RxRegistrationChargeCategoryRecordReq;
import com.xyht.sca_s.student_manage_system.modules.rxRegistration.entity.resp.RxRegistrationChargeCategoryDetailJsonResp;
import com.xyht.sca_s.student_manage_system.modules.rxRegistration.entity.resp.RxRegistrationChargeCategoryDetailResp;
import com.xyht.sca_s.student_manage_system.modules.rxRegistration.entity.resp.RxRegistrationChargeCategoryRecordResp;
import com.xyht.sca_s.student_manage_system.modules.rxRegistration.entity.resp.RxRegistrationChargeCategoryResp;
import com.xyht.sca_s.student_manage_system.modules.rxRegistration.mapper.*;
import com.xyht.sca_s.student_manage_system.modules.rxRegistration.service.RxRegistrationChargeCategoryRecordService;
import com.xyht.sca_s.student_manage_system.modules.rxRegistrationAdvance.entity.RxRegistrationAdvanceStudentInfo;
import com.xyht.sca_s.student_manage_system.modules.rxRegistrationAdvance.entity.req.RxRegistrationAdvanceCustomColumnValueReq;
import com.xyht.sca_s.student_manage_system.modules.rxRegistrationAdvance.entity.req.RxRegistrationAdvanceStudentInfoAddReq;
import com.xyht.sca_s.student_manage_system.modules.rxRegistrationAdvance.entity.resp.RxRegistrationAdvanceCustomColumnValueResp;
import com.xyht.sca_s.student_manage_system.modules.rxRegistrationAdvance.entity.resp.RxRegistrationAdvanceStudentInfoResp;
import com.xyht.sca_s.student_manage_system.modules.rxRegistrationAdvance.mapper.RxRegistrationAdvanceStudentInfoMapper;
import com.xyht.sca_s.student_manage_system.modules.rxRegistrationAdvance.util.PlanUtil;
import com.xyht.sca_s.student_manage_system.modules.rxRegistrationChargePayment.entity.req.RxRegistrationChargePaymentCategoryDivideReq;
import com.xyht.sca_s.student_manage_system.modules.rxRegistrationChargePayment.entity.req.RxRegistrationChargePaymentRecordReq;
import com.xyht.sca_s.student_manage_system.modules.rxRegistrationChargePayment.entity.resp.RxRegistrationPrepayPaymentResp;
import com.xyht.sca_s.student_manage_system.modules.rxRegistrationChargePayment.util.PaymentUtil;
import com.xyht.sca_s.student_manage_system.modules.rxRegistrationExamine.entity.RxRegistrationExamineBlackList;
import com.xyht.sca_s.student_manage_system.modules.rxRegistrationExamine.mapper.RxRegistrationExamineBlackListMapper;
import com.xyht.sca_s.student_manage_system.modules.rxRegistrationWelcome.entity.RxRegistrationWelcome;
import com.xyht.sca_s.student_manage_system.modules.rxRegistrationWelcome.entity.req.*;
import com.xyht.sca_s.student_manage_system.modules.rxRegistrationWelcome.entity.resp.RxRegistrationAdvanceStudentInfoGroupClassResp;
import com.xyht.sca_s.student_manage_system.modules.rxRegistrationWelcome.entity.resp.RxRegistrationPlanChargeCategoryResp;
import com.xyht.sca_s.student_manage_system.modules.rxRegistrationWelcome.entity.resp.RxRegistrationStudentInfoResp;
import com.xyht.sca_s.student_manage_system.modules.rxRegistrationWelcome.mapper.RxRegistrationWelcomeMapper;
import com.xyht.sca_s.student_manage_system.modules.rxRegistrationWelcome.mapper.RxRegistrationWelcomeReductionMapper;
import com.xyht.sca_s.student_manage_system.modules.rxRegistrationWelcome.service.RxRegistrationWelcomeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xyht.sca_s.student_manage_system.modules.rxRegistrationWelcome.util.WelcomeStuUtil;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.beans.BeanUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Future;
import java.util.stream.Collectors;

import static com.xyht.sca_s.student_manage_system.common.util.ParamCheckUtil.isNullOrEmpty;
import static com.xyht.sca_s.student_manage_system.modules.common.constant.TaskDetailReason.*;
import static com.xyht.sca_s.student_manage_system.modules.common.constant.TaskNameExample.TASK_NAME_WELCOME_GROUP_CLASS_IMPORT;
import static com.xyht.sca_s.student_manage_system.modules.common.constant.TaskStatus.TASK_STATUS_DONE;
import static com.xyht.sca_s.student_manage_system.modules.common.constant.TaskStatus.TASK_STATUS_ERR;
import static com.xyht.sca_s.student_manage_system.modules.common.constant.TaskTypeConstant.TASK_TYPE_REGISTRATION_GROUP_CLASS_IMPORT;
import static com.xyht.sca_s.student_manage_system.modules.rxRegistration.constant.AppTypeConstant.*;
import static com.xyht.sca_s.student_manage_system.modules.rxRegistration.constant.ChargeCategoryTypeConstant.*;
import static com.xyht.sca_s.student_manage_system.modules.rxRegistration.constant.ChargeCategoryTypeConstant.CHARGE_CATEGORY_TYPE_NORMAL;
import static com.xyht.sca_s.student_manage_system.modules.rxRegistration.constant.PlanStatusConstant.PLAN_STATUS_ENABLE;
import static com.xyht.sca_s.student_manage_system.modules.rxRegistrationAdvance.constant.RegistrationStatusConstant.REGISTRATION_STATUS_FINISH;
import static com.xyht.sca_s.student_manage_system.modules.rxRegistrationAdvance.constant.RegistrationStatusConstant.REGISTRATION_STATUS_GOING_ON;
import static com.xyht.sca_s.student_manage_system.modules.rxRegistrationChargePayment.constant.PaymentTypeConstant.*;
import static com.xyht.sca_s.student_manage_system.modules.rxRegistrationWelcome.constant.AllowStatusConstant.ALLOW_STATUS_PASS;
import static com.xyht.sca_s.student_manage_system.modules.rxRegistrationWelcome.constant.IsGroupClassConstant.GROUP_CLASS;
import static com.xyht.sca_s.student_manage_system.modules.rxRegistrationWelcome.constant.IsGroupClassConstant.GROUP_CLASS_NOT;
import static com.xyht.sca_s.student_manage_system.modules.rxRegistrationWelcome.constant.IsStayConstant.IS_STAY;
import static com.xyht.sca_s.student_manage_system.modules.rxRegistrationWelcome.constant.IsStayConstant.IS_STAY_NO;
import static com.xyht.sca_s.student_manage_system.modules.signUp.constant.SmsSignUpCommonConstant.PER_SHEET_NUM;

/**
 * <p>
 * 招生管理迎新管理 服务实现类
 * </p>
 *
 * @author XYHT
 * @since 2024-05-16
 */
@Service
public class RxRegistrationWelcomeServiceImpl extends ServiceImpl<RxRegistrationWelcomeMapper, RxRegistrationWelcome> implements RxRegistrationWelcomeService {

    @Resource
    private RxRegistrationAdvanceStudentInfoMapper rxRegistrationAdvanceStudentInfoMapper;
    @Resource
    private ApiModelUtil apiModelUtil;
    @Resource
    private SmsImportTaskMapper smsImportTaskMapper;
    @Resource
    private SmsImportTaskDetailMapper smsImportTaskDetailMapper;
    @Resource
    private PlatformTransactionManager transactionManager;
    @Resource
    private RxRegistrationPlanSettingMapper rxRegistrationPlanSettingMapper;
    @Resource
    private RxAdvanceRegistrationOrgMapper rxAdvanceRegistrationOrgMapper;
    @Resource
    private WelcomeStuUtil welcomeStuUtil;
    @Resource
    private PlanUtil planUtil;
    @Resource
    private RxRegistrationExamineBlackListMapper rxRegistrationExamineBlackListMapper;
    @Resource
    private RxRegistrationPlanAppSettingMapper rxRegistrationPlanAppSettingMapper;
    @Resource
    private PaymentUtil paymentUtil;
    @Resource
    private RxRegistrationCustomColumnMapper rxRegistrationCustomColumnMapper;
    @Resource
    private RxRegistrationCustomColumnValueMapper rxRegistrationCustomColumnValueMapper;
    @Resource
    private RxRegistrationWelcomeReductionMapper rxRegistrationWelcomeReductionMapper;
    @Resource
    private RxRegistrationPlanChargeCategorySettingMapper rxRegistrationPlanChargeCategorySettingMapper;
    @Resource
    private RxRegistrationChargeCategoryRecordMapper rxRegistrationChargeCategoryRecordMapper;
    @Resource
    private RxRegistrationChargeCategoryRecordService rxRegistrationChargeCategoryRecordService;

    @Override
    @Async
    public Future<ResponseResult> exportStuInfo(RxRegistrationAdvanceStudentInfoGroupClassExportReq exportReq, HttpServletResponse response) {
        try {

            if (isNullOrEmpty(exportReq.getPlanId())) {
                return new AsyncResult<>(CommonResult.failed(CommonCodeEnum.INVALID_PARAM));
            }
            LambdaQueryWrapper<RxRegistrationAdvanceStudentInfo> studentInfoLambdaQueryWrapper =
                    new LambdaQueryWrapper<RxRegistrationAdvanceStudentInfo>()
                            .eq(RxRegistrationAdvanceStudentInfo::getPlanId,exportReq.getPlanId());

            if (!isNullOrEmpty(exportReq.getOrgId())) {
                studentInfoLambdaQueryWrapper.eq(RxRegistrationAdvanceStudentInfo::getOrgId,exportReq.getOrgId());
            }

            if (!isNullOrEmpty(exportReq.getMiddleSchoolId())) {
                studentInfoLambdaQueryWrapper.eq(RxRegistrationAdvanceStudentInfo::getMiddleSchoolId,exportReq.getMiddleSchoolId());
            }

            if (!isNullOrEmpty(exportReq.getIsGroupClass())) {
                studentInfoLambdaQueryWrapper.eq(RxRegistrationAdvanceStudentInfo::getIsGroupClass,exportReq.getIsGroupClass());
            }

            List<RxRegistrationAdvanceStudentInfoGroupClassResp> list = rxRegistrationAdvanceStudentInfoMapper.selectList(studentInfoLambdaQueryWrapper)
                    .stream()
                    .map(rxRegistrationAdvanceStudentInfo -> {
                        RxRegistrationAdvanceStudentInfoGroupClassResp resp = new RxRegistrationAdvanceStudentInfoGroupClassResp();
                        BeanUtils.copyProperties(rxRegistrationAdvanceStudentInfo, resp);
                        return resp;
                    })
                    .collect(Collectors.toList());

        //表头数据
        String[] header = exportReq.getLimitColumn().toArray(new String[0]);
        double sheetNum;
        //声明一个工作簿
        HSSFWorkbook workbook = new HSSFWorkbook();
        if (list.size() > 0) {
            sheetNum = Math.ceil((double) list.size() / PER_SHEET_NUM);
            for (int k = 0; k < sheetNum; k++) {
                //生成一个表格，设置表格名称为"资源导出表"
                HSSFSheet sheet = workbook.createSheet("学生分班信息导出表" + (k + 1));

                //设置表格列宽度为10个字节
                sheet.setDefaultColumnWidth(12);
                //创建标题的显示样式
                HSSFCellStyle headerStyle = workbook.createCellStyle();
                headerStyle.setFillForegroundColor(IndexedColors.YELLOW.index);
                headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);

                HSSFFont f = workbook.createFont();
                f.setFontHeightInPoints((short) 10);//字号
                f.setBold(true);//加粗
                headerStyle.setFont(f);
                //创建第一行表头
                HSSFRow remarkRow = sheet.createRow(0);
                remarkRow.setHeightInPoints((float) 40.0);
                // 设置行的自动高度
//                remarkRow.setHeight((short)20);
                Cell remarkCell = remarkRow.createCell(0); // A1 单元格
                remarkCell.setCellValue("1:分班专业名称必须存在\n"
                        +"2:学生基本信息不允许修改,只可填写分班专业、分班年级、分班班级");

                // 合并A1到D1四个单元格
                int numColumnsToMerge = 5; // 要合并的列数
                CellRangeAddress region = new CellRangeAddress(
                        0, // 起始行索引
                        0, // 结束行索引
                        0, // 起始列索引
                        numColumnsToMerge - 1); // 结束列索引
                sheet.addMergedRegion(region);

                CellStyle style = workbook.createCellStyle();
                style.setWrapText(true);//换行
                style.setAlignment(HorizontalAlignment.LEFT); // 水平左对齐
                style.setVerticalAlignment(VerticalAlignment.CENTER); // 垂直居中
                remarkCell.setCellStyle(style);
                //创建第一行表头
                HSSFRow headrow = sheet.createRow(1);

                //遍历添加表头(下面模拟遍历学生，也是同样的操作过程)
                for (int i = 0; i < header.length + 1; i++) {
                    //创建一个单元格
                    HSSFCell cell = headrow.createCell(i);

                    if (i == 0) {
                        //创建一个内容对象
                        HSSFRichTextString text = new HSSFRichTextString("序号");
                        //将内容对象的文字内容写入到单元格中
                        cell.setCellValue(text);
                        cell.setCellStyle(headerStyle);
                        continue;
                    }
                    //创建一个内容对象
                    String header1 = apiModelUtil.getFieldValueByFieldName(RxRegistrationAdvanceStudentInfoGroupClassResp.class, header[i - 1]);
                    HSSFRichTextString text = new HSSFRichTextString(header1);

                    //将内容对象的文字内容写入到单元格中
                    cell.setCellValue(text);
                    cell.setCellStyle(headerStyle);

                }



                int range = PER_SHEET_NUM;
                if (k + 1 == sheetNum) {
                    range = list.size() - (PER_SHEET_NUM) * k;
                }
                for (int i = 0; i < range; i++) {

                    //创建一行
                    HSSFRow row1 = sheet.createRow(i + 2);
                    RxRegistrationAdvanceStudentInfoGroupClassResp groupClassResp = list.get((PER_SHEET_NUM) * k + i);
                    Map map = JSONObject.parseObject(JSON.toJSONString(groupClassResp), Map.class);
                    row1.createCell(0).setCellValue(new HSSFRichTextString(i + 1 + ""));
                    for (int j = 0; j < header.length; j++) {
                        String rowContent = "";
                        if(!isNullOrEmpty(map.get(header[j]))) {
                            if (map.get(header[j]) instanceof Long) {
                                rowContent = TimeUtil.DateAllHanZi((long) map.get(header[j]));
                            } else {
                                rowContent = String.valueOf(map.get(header[j]));
                            }
                        }
                        row1.createCell(j + 1).setCellValue(new HSSFRichTextString(rowContent));
                    }
                }
            }
        }


        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("学生学生分班信息导出表.xlsx", "utf-8"));
        response.setCharacterEncoding("utf-8");
        response.setHeader("file-type", "download");
        response.setHeader("file-name", URLEncoder.encode("学生分班信息导出表.xlsx", "utf-8"));
        response.setHeader("Access-Control-Expose-Headers", "file-type,file-name");
        //刷新缓冲
        response.flushBuffer();
        //workbook将Excel写入到response的输出流中，供页面下载
        OutputStream os = response.getOutputStream();
        workbook.write(os);

        workbook.close();
        os.close();
    } catch (Exception e) {
        e.printStackTrace();
        return new AsyncResult<>(CommonResult.failed(CommonCodeEnum.FAIL));
    }
        return null;
    }

    @Override
    @Async
    public Future<ResponseResult> batchAddGroupClass(RxRegistrationAdvanceStudentInfoGroupClassBatchReq groupClassBatchReq, String user_id) {

        if (isNullOrEmpty(groupClassBatchReq)) {
            return new AsyncResult<>(CommonResult.failed(CommonCodeEnum.INVALID_PARAM));
        }
        String planId = groupClassBatchReq.getPlanId();
        RxRegistrationPlanSetting planSetting = rxRegistrationPlanSettingMapper.selectById(planId);
        if (isNullOrEmpty(planSetting)) {
            return new AsyncResult<>(CommonResult.failed(CommonCodeEnum.RX_REGISTRATION_ADVANCE_PLAN_NOT_EXIST));
        }
        List<RxRegistrationAdvanceStudentInfoGroupClassInfoResp> groupClassInfoList = groupClassBatchReq.getGroupClassInfoList();
        if (groupClassInfoList == null || groupClassInfoList.size() < 1) {
            return new AsyncResult<>(CommonResult.failed(CommonCodeEnum.INVALID_PARAM));
        }
        //创建导入任务
        SmsImportTask smsImportTask = new SmsImportTask();
        smsImportTask.setTaskName(TASK_NAME_WELCOME_GROUP_CLASS_IMPORT);
        smsImportTask.setUserId(user_id);
        smsImportTask.setTaskType(TASK_TYPE_REGISTRATION_GROUP_CLASS_IMPORT);
        smsImportTaskMapper.insert(smsImportTask);
        batchAddGroupClassInfo(groupClassInfoList, planId, smsImportTask.getId(),user_id);
        return new AsyncResult<>(CommonResult.success());
    }

    private void batchAddGroupClassInfo( List<RxRegistrationAdvanceStudentInfoGroupClassInfoResp> groupClassInfoList,String planId, String id, String userId) {
        int OFFSET_ROW = 2;
        int task_status = TASK_STATUS_DONE;
        for (int i = 0; i < groupClassInfoList.size(); i++) {
            //开启事务
            DefaultTransactionDefinition dt = new DefaultTransactionDefinition();
            // 嵌套事务 PROPAGATION_REQUIRES_NEW 每次开启一个新的事务
            dt.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
            // 设置嵌套事务
            TransactionStatus status = transactionManager.getTransaction(dt);
            try {
                RxRegistrationAdvanceStudentInfoGroupClassInfoResp storage = groupClassInfoList.get(i);
                if (isNullOrEmpty(storage.getIdCard(), storage.getGroupMajor())) {
                    transactionManager.rollback(status);
                    task_status = TASK_STATUS_ERR;
                    createTeacherImportTaskDetail(id, REASON_INVALID_PARAM, (i + OFFSET_ROW) + "");
                    continue;
                }


                //身份证号
                LambdaQueryWrapper<RxRegistrationAdvanceStudentInfo> studentInForLambdaQueryWrapper = new LambdaQueryWrapper<>();
                studentInForLambdaQueryWrapper.eq(RxRegistrationAdvanceStudentInfo::getIdCard, storage.getIdCard())
                        .eq(RxRegistrationAdvanceStudentInfo::getPlanId, planId);
                List<RxRegistrationAdvanceStudentInfo> studentInfoList = rxRegistrationAdvanceStudentInfoMapper.selectList(studentInForLambdaQueryWrapper);
                if (studentInfoList == null || studentInfoList.size() < 1) {
                    transactionManager.rollback(status);
                    task_status = TASK_STATUS_ERR;
                    createTeacherImportTaskDetail(id, REASON_REGISTRATION_STUDENT_NOT_EXIST, (i + OFFSET_ROW) + "");
                    continue;
                }

                //校验专业
                List<RxAdvanceRegistrationOrg> registrationOrgList = rxAdvanceRegistrationOrgMapper.selectList(new LambdaQueryWrapper<RxAdvanceRegistrationOrg>()
                        .eq(RxAdvanceRegistrationOrg::getMajorName, storage.getGroupMajor()));
                if (registrationOrgList == null || registrationOrgList.size() < 1) {
                    transactionManager.rollback(status);
                    task_status = TASK_STATUS_ERR;
                    createTeacherImportTaskDetail(id, REASON_ADVANCE_REGISTRATION_ORG_NOT_EXIST, (i + OFFSET_ROW) + "");
                    continue;
                }
                //校验分班专业是否设置了对应的收费项
                //是否设置了专业收费项
                List<RxRegistrationPlanChargeCategorySetting> categorySettingList = rxRegistrationPlanChargeCategorySettingMapper.selectList(new LambdaQueryWrapper<RxRegistrationPlanChargeCategorySetting>()
                        .eq(RxRegistrationPlanChargeCategorySetting::getPlanId, planId)
                        .eq(RxRegistrationPlanChargeCategorySetting::getAppType, APP_TYPE_WELCOME)
                        .eq(RxRegistrationPlanChargeCategorySetting::getChargeCategoryType, CHARGE_CATEGORY_TYPE_MAJOR));
                if (categorySettingList == null || categorySettingList.size() < 1) {
                    transactionManager.rollback(status);
                    task_status = TASK_STATUS_ERR;
                    createTeacherImportTaskDetail(id, REASON_REGISTRATION_CATEGORY_MAJOR_NOT_EXIST, (i + OFFSET_ROW) + "");
                    continue;
                }
                //校验所分班的专业是否设置了对应的子项收费
                RxRegistrationPlanChargeCategorySetting chargeCategorySetting = categorySettingList.get(0);
                List<RxRegistrationChargeCategoryDetailJsonResp> childrenList = JSONObject.parseArray(chargeCategorySetting.getChargeCategoryChildren(), RxRegistrationChargeCategoryDetailJsonResp.class);
                List<RxRegistrationChargeCategoryDetailJsonResp> majorCategoryList = childrenList.stream().filter(children -> children.getChargeCategoryName().equals(storage.getGroupMajor())).collect(Collectors.toList());
                if (majorCategoryList.size() < 1) {
                    transactionManager.rollback(status);
                    task_status = TASK_STATUS_ERR;
                    createTeacherImportTaskDetail(id, REASON_REGISTRATION_CATEGORY_MAJOR_NOT_EXIST, (i + OFFSET_ROW) + "");
                    continue;
                }
                RxRegistrationAdvanceStudentInfo rxRegistrationAdvanceStudentInfo = new RxRegistrationAdvanceStudentInfo();
                rxRegistrationAdvanceStudentInfo.setGroupMajor(storage.getGroupMajor());
                rxRegistrationAdvanceStudentInfo.setGroupGrade(storage.getGroupGrade());
                rxRegistrationAdvanceStudentInfo.setGroupClass(storage.getGroupClass());
                rxRegistrationAdvanceStudentInfo.setIsGroupClass(GROUP_CLASS);
                rxRegistrationAdvanceStudentInfoMapper.update(rxRegistrationAdvanceStudentInfo,studentInForLambdaQueryWrapper);


                transactionManager.commit(status);
            } catch (Exception e) {
                transactionManager.rollback(status);
                task_status = TASK_STATUS_ERR;
                createTeacherImportTaskDetail(id, REASON_IMPORT_ERR, (i + OFFSET_ROW) + "");
            } finally {
                if (status.isNewTransaction() && !status.isCompleted()) {
                    transactionManager.commit(status);
                }
            }
        }
        SmsImportTask smsImportTask = new SmsImportTask();
        smsImportTask.setId(id);
        smsImportTask.setStatus(task_status);
        smsImportTaskMapper.updateById(smsImportTask);
    }

    private void createTeacherImportTaskDetail(String id, String reason, String row) {
        SmsImportTaskDetail smsImportTaskDetail = new SmsImportTaskDetail();
        smsImportTaskDetail.setTaskId(id);
        smsImportTaskDetail.setFailReason(reason);
        smsImportTaskDetail.setFailRow(row);
        smsImportTaskDetailMapper.insert(smsImportTaskDetail);
    }
    @Override
    public ResponseResult groupClass(RxRegistrationAdvanceStudentInfoGroupClassReq groupClassReq) {
        if (isNullOrEmpty(groupClassReq.getStuId(),groupClassReq.getGroupMajor())) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        RxRegistrationAdvanceStudentInfo rxRegistrationAdvanceStudentInfo = rxRegistrationAdvanceStudentInfoMapper.selectById(groupClassReq.getStuId());
        if (isNullOrEmpty(rxRegistrationAdvanceStudentInfo)) {
            return CommonResult.failed(CommonCodeEnum.RX_REGISTRATION_ADVANCE_STUDENT_NOT_EXIT);
        }
        //校验专业
        List<RxAdvanceRegistrationOrg> registrationOrgList = rxAdvanceRegistrationOrgMapper.selectList(new LambdaQueryWrapper<RxAdvanceRegistrationOrg>()
                .eq(RxAdvanceRegistrationOrg::getMajorName, groupClassReq.getGroupMajor()));
        if (registrationOrgList == null || registrationOrgList.size() < 1) {
           return CommonResult.failed(CommonCodeEnum.ADVANCE_REGISTRATION_ORG_NOT_EXIST);
        }
        //校验分班专业是否设置了对应的收费项
        //是否设置了专业收费项
        List<RxRegistrationPlanChargeCategorySetting> categorySettingList = rxRegistrationPlanChargeCategorySettingMapper.selectList(new LambdaQueryWrapper<RxRegistrationPlanChargeCategorySetting>()
                .eq(RxRegistrationPlanChargeCategorySetting::getPlanId, rxRegistrationAdvanceStudentInfo.getPlanId())
                .eq(RxRegistrationPlanChargeCategorySetting::getAppType, APP_TYPE_WELCOME)
                .eq(RxRegistrationPlanChargeCategorySetting::getChargeCategoryType, CHARGE_CATEGORY_TYPE_MAJOR));
        if (categorySettingList == null || categorySettingList.size() < 1) {
            return CommonResult.failed(CommonCodeEnum.RX_REGISTRATION_CHARGE_CATEGORY_TYPE_MAJOR_NOT_EXIT);
        }
        //校验所分班的专业是否设置了对应的子项收费
        RxRegistrationPlanChargeCategorySetting chargeCategorySetting = categorySettingList.get(0);
        List<RxRegistrationChargeCategoryDetailJsonResp> childrenList = JSONObject.parseArray(chargeCategorySetting.getChargeCategoryChildren(), RxRegistrationChargeCategoryDetailJsonResp.class);
        List<RxRegistrationChargeCategoryDetailJsonResp> majorCategoryList = childrenList.stream().filter(children -> children.getChargeCategoryName().equals(groupClassReq.getGroupMajor())).collect(Collectors.toList());
        if (majorCategoryList.size() < 1) {
            return CommonResult.failed(CommonCodeEnum.RX_REGISTRATION_CHARGE_CATEGORY_TYPE_MAJOR_NOT_EXIT);
        }
        rxRegistrationAdvanceStudentInfo.setGroupClass(groupClassReq.getGroupClass());
        rxRegistrationAdvanceStudentInfo.setGroupMajor(groupClassReq.getGroupMajor());
        rxRegistrationAdvanceStudentInfo.setGroupGrade(groupClassReq.getGroupGrade());
        rxRegistrationAdvanceStudentInfo.setIsGroupClass(GROUP_CLASS);
        rxRegistrationAdvanceStudentInfoMapper.updateById(rxRegistrationAdvanceStudentInfo);
        return CommonResult.success();
    }


    @Override
    public ResponseResult getGroupClassList(Integer pageSize, Integer pageNum, String stuName, Integer isGroupClass, String idCard, String middleSchoolId, String majorId, String planId) {
        if (isNullOrEmpty(planId)) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        Page<RxRegistrationAdvanceStudentInfo> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<RxRegistrationAdvanceStudentInfo> studentInfoLambdaQueryWrapper = new LambdaQueryWrapper<RxRegistrationAdvanceStudentInfo>()
                .eq(RxRegistrationAdvanceStudentInfo::getPlanId,planId)
                .orderByDesc(RxRegistrationAdvanceStudentInfo::getCreateTime);

        if (!isNullOrEmpty(stuName)) {
            studentInfoLambdaQueryWrapper.like(RxRegistrationAdvanceStudentInfo::getName, stuName);
        }

        if (!isNullOrEmpty(isGroupClass)) {
            studentInfoLambdaQueryWrapper.eq(RxRegistrationAdvanceStudentInfo::getIsGroupClass, isGroupClass);
        }

        if (!isNullOrEmpty(idCard)) {
            studentInfoLambdaQueryWrapper.eq(RxRegistrationAdvanceStudentInfo::getIdCard, idCard);
        }

        if (!isNullOrEmpty(majorId)) {
            studentInfoLambdaQueryWrapper.eq(RxRegistrationAdvanceStudentInfo::getOrgId, majorId);
        }

        if (!isNullOrEmpty(middleSchoolId)) {
            studentInfoLambdaQueryWrapper.eq(RxRegistrationAdvanceStudentInfo::getMiddleSchoolId, middleSchoolId);
        }
        rxRegistrationAdvanceStudentInfoMapper.selectPage(page, studentInfoLambdaQueryWrapper);
        List<RxRegistrationStudentInfoResp> list = page.getRecords()
                .stream()
                .map(rxRegistrationAdvanceStudentInfo -> {
                    RxRegistrationStudentInfoResp resp = new RxRegistrationStudentInfoResp();
                    BeanUtils.copyProperties(rxRegistrationAdvanceStudentInfo, resp);
                    return resp;
                })
                .collect(Collectors.toList());
        return CommonResult.success(list, (int)page.getTotal());
    }

    @Override
    public ResponseResult getWelcomeStuInfo(String idCard) {

        RxRegistrationAdvanceStudentInfoResp rxRegistrationAdvanceStudentInfoResp = new RxRegistrationAdvanceStudentInfoResp();
        //计划
        RxRegistrationPlanSetting planSetting = planUtil.getEnablePlanInfo();
        if (planSetting == null) {
            return CommonResult.failed(CommonCodeEnum.RX_REGISTRATION_ADVANCE_PLAN_NOT_EXIST);
        }
        String planId = planSetting.getId();
        rxRegistrationAdvanceStudentInfoResp.setPlanId(planId);
        //学生信息
        if (isNullOrEmpty(idCard)) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        //身份证
        boolean validIDCard = ParamCheckUtil.isValidIDCard(idCard);
        if (!validIDCard) {
            return CommonResult.failed(CommonCodeEnum.ENROLLMENT_MANAGEMENT_STUDENT_ID_CARD_ERR);
        }
        //学生信息
        if (isNullOrEmpty(idCard)) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        // 判断是否在黑名单中
        List<RxRegistrationExamineBlackList> blackList = rxRegistrationExamineBlackListMapper.selectList(new LambdaQueryWrapper<RxRegistrationExamineBlackList>()
                .eq(RxRegistrationExamineBlackList::getStuIdCard, idCard));
        if (blackList != null && blackList.size() > 0) {
            return CommonResult.failed(CommonCodeEnum.RX_REGISTRATION_BLACK_LIST_STUDENT_EXIST);
        }

        //获取招生计划下阶段招生开放时间
        Date nowDate = new Date();
        List<RxRegistrationPlanAppSetting> planAppSettingList = rxRegistrationPlanAppSettingMapper.selectList(new LambdaQueryWrapper<RxRegistrationPlanAppSetting>()
                .eq(RxRegistrationPlanAppSetting::getPlanId, planId)
                .lt(RxRegistrationPlanAppSetting::getBgTime, nowDate) //开始时间小于当前时间
                .gt(RxRegistrationPlanAppSetting::getEndTime, nowDate)  //结束时间大于当前时间
                .orderByDesc(RxRegistrationPlanAppSetting::getAppType));
        if (planAppSettingList == null || planAppSettingList.size() == 0) {
            return CommonResult.failed(CommonCodeEnum.RX_REGISTRATION_ADVANCE_NOT_SUBMIT);
        }

        //获取自定义字段
        List<RxRegistrationAdvanceCustomColumnValueResp> welcomeStuCustomColumnValueList = welcomeStuUtil.getWelcomeStuCustomColumnValueList(idCard);
        rxRegistrationAdvanceStudentInfoResp.setCustomColumnValueList(welcomeStuCustomColumnValueList);

        RxRegistrationAdvanceStudentInfo studentInfo ;
        List<RxRegistrationAdvanceStudentInfo> studentInfoList = rxRegistrationAdvanceStudentInfoMapper.selectList(new LambdaQueryWrapper<RxRegistrationAdvanceStudentInfo>()
                .eq(RxRegistrationAdvanceStudentInfo::getIdCard, idCard)
                .eq(RxRegistrationAdvanceStudentInfo::getPlanId, planId));
        if (studentInfoList != null && studentInfoList.size() > 0) {
            studentInfo = studentInfoList.get(0);
            BeanUtils.copyProperties(studentInfo, rxRegistrationAdvanceStudentInfoResp);
            rxRegistrationAdvanceStudentInfoResp.setStuId(studentInfoList.get(0).getId());
        }else {
            return CommonResult.success(rxRegistrationAdvanceStudentInfoResp);
        }
        //未分班则显示学生基本信息
        if (studentInfo.getIsGroupClass() == GROUP_CLASS_NOT) {
            return CommonResult.success(rxRegistrationAdvanceStudentInfoResp);
        }
        //封装缴费项记录信息
        rxRegistrationAdvanceStudentInfoResp.setChargeCategoryRecordRespList(getChargeCategoryRecordList(studentInfo));

        //获取收费项
        RxRegistrationAdvanceStudentInfoResp resp = welcomeStuUtil.getWelcomeAllStuPaymentCategory(studentInfo);

        rxRegistrationAdvanceStudentInfoResp.setIsSetMajor(resp.getIsSetMajor());
        rxRegistrationAdvanceStudentInfoResp.setChargeCategoryRespList(resp.getChargeCategoryRespList());
        return CommonResult.success(rxRegistrationAdvanceStudentInfoResp);
    }

    @Override
    @Transactional
    public ResponseResult welComePayment(RxRegistrationAdvanceStudentInfoAddReq req) {
        //校验学生信息
        //学生id
        String stuId = req.getStuId();
        if (isNullOrEmpty(req.getStuId())) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        RxRegistrationAdvanceStudentInfo rxRegistrationAdvanceStudentInfo = rxRegistrationAdvanceStudentInfoMapper.selectById(stuId);
        if (isNullOrEmpty(rxRegistrationAdvanceStudentInfo)) {
            return CommonResult.failed(CommonCodeEnum.ADVANCE_REGISTRATION_DATA_UPDATE);
        }

        //缴费状态  0:未完成 1:进行中 2: 完成
        Integer advanceStatus = rxRegistrationAdvanceStudentInfo.getAdvanceStatus();//预报名阶段状态
        Integer confirmStatus = rxRegistrationAdvanceStudentInfo.getConfirmStatus();  //确认报名
        Integer welcomeStatus = rxRegistrationAdvanceStudentInfo.getWelcomeStatus();//迎新报名
        //如果三个阶段都缴费则不允许再次提交
        if (advanceStatus == REGISTRATION_STATUS_FINISH && confirmStatus == REGISTRATION_STATUS_FINISH && welcomeStatus == REGISTRATION_STATUS_FINISH) {
            return CommonResult.failed(CommonCodeEnum.ADVANCE_REGISTRATION_HAS_PAYED);
        }
        //先判断学生是否申请减免 缓交 只有通过才判断
        Integer delayStatus = rxRegistrationAdvanceStudentInfo.getDelayStatus(); //缓交状态
        //缓交通过时
        if (delayStatus == ALLOW_STATUS_PASS) {
            return CommonResult.failed(CommonCodeEnum.RX_REGISTRATION_WELCOME_DELAY_NOT_PAYED);
        }
        //校验是否分班
        Integer isGroupClass = rxRegistrationAdvanceStudentInfo.getIsGroupClass();
        if (isGroupClass == GROUP_CLASS_NOT) {
            return CommonResult.failed(CommonCodeEnum.ADVANCE_REGISTRATION_NOT_GROUP_CLASS);
        }
        //判断是否设置了分班的专业收费项

        //校验必要数据
        checkRequiredInfo(req);
        if (isNullOrEmpty(req.getOpenId())) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }

        //校验计划
        String planId = req.getPlanId();
        //查询计划是否存在并启用
        List<RxRegistrationPlanSetting> planSettingList = rxRegistrationPlanSettingMapper.selectList(new LambdaQueryWrapper<RxRegistrationPlanSetting>()
                .eq(RxRegistrationPlanSetting::getId, planId)
                .eq(RxRegistrationPlanSetting::getPlanStatus, PLAN_STATUS_ENABLE));
        String planName = planSettingList.get(0).getPlanName();
        //校验组织
        String orgName = null;
        if (!isNullOrEmpty(req.getOrgId())) {
            RxAdvanceRegistrationOrg advanceRegistrationOrg = rxAdvanceRegistrationOrgMapper.selectById(req.getOrgId());
            if (isNullOrEmpty(advanceRegistrationOrg)) {
                ExceptionCast.cast(CommonResult.failed(CommonCodeEnum.ADVANCE_REGISTRATION_ORG_NOT_EXIST));
            }
            orgName = advanceRegistrationOrg.getMajorName();
        }

        // 获取商户集合
        List<WxPayFunctions> wxPayFunctionsList = WxPayConfig.wxPayFunctionsList;
        if (wxPayFunctionsList.isEmpty()) {
            ExceptionCast.cast(CommonResult.failed(CommonCodeEnum.FAIL));
        }
        // 校验前端传入的商户Type
        RxRegistrationPlanSetting enablePlanInfo = planUtil.getEnablePlanInfo();
        if (enablePlanInfo == null) {
            ExceptionCast.cast(CommonResult.failed(CommonCodeEnum.RX_REGISTRATION_ADVANCE_PLAN_NOT_EXIST));
        }
        Integer wxPayFunctionSort = enablePlanInfo.getPlanChargeShopSort();
        if (wxPayFunctionSort == null || wxPayFunctionSort <= 0
                || wxPayFunctionSort > wxPayFunctionsList.size() + 1) {
            ExceptionCast.cast(CommonResult.failed(CommonCodeEnum.INVALID_PARAM));
        }
        // 获取用户选择的商户
        WxPayFunctions wxPayFunction = wxPayFunctionsList.get(wxPayFunctionSort - 1);


        //构造支付参数
        RxRegistrationChargePaymentRecordReq recordReq = new RxRegistrationChargePaymentRecordReq();
        List<RxRegistrationChargePaymentCategoryDivideReq> divideReqList ;
        //获取自定义必填字段
        List<RxRegistrationAdvanceCustomColumnValueReq> customColumnValueList = req.getCustomColumnValueList();//传入的自定义字段

        //修改学生信息
        BeanUtils.copyProperties(req, rxRegistrationAdvanceStudentInfo);
        rxRegistrationAdvanceStudentInfo.setPlanName(planName);
        rxRegistrationAdvanceStudentInfo.setOrgName(orgName);
        rxRegistrationAdvanceStudentInfoMapper.updateById(rxRegistrationAdvanceStudentInfo);

        //修改该学生自定义信息
        if (customColumnValueList != null && customColumnValueList.size() > 0) {
            for (RxRegistrationAdvanceCustomColumnValueReq rxRegistrationAdvanceCustomColumnValueReq : customColumnValueList) {
                RxRegistrationCustomColumnValue rxRegistrationCustomColumnValue = new RxRegistrationCustomColumnValue();
                BeanUtils.copyProperties(rxRegistrationAdvanceCustomColumnValueReq, rxRegistrationCustomColumnValue);
                if (isNullOrEmpty(rxRegistrationAdvanceCustomColumnValueReq.getId())) {
                    rxRegistrationCustomColumnValue.setPlanId(planId);
                    rxRegistrationCustomColumnValue.setStudentId(stuId);
                    rxRegistrationCustomColumnValueMapper.insert(rxRegistrationCustomColumnValue);
                }else {
                    rxRegistrationCustomColumnValueMapper.update(rxRegistrationCustomColumnValue, new LambdaQueryWrapper<RxRegistrationCustomColumnValue>()
                            .eq(RxRegistrationCustomColumnValue::getPlanId, planId)
                            .eq(RxRegistrationCustomColumnValue::getStudentId, stuId)
                            .eq(RxRegistrationCustomColumnValue::getColumnId, rxRegistrationAdvanceCustomColumnValueReq.getColumnId()));
                }
            }
        }

        // 获取收费项
        divideReqList = chargeCategoryOperation(stuId,req.getChargeCategoryRecordList());

        //支付所需的信息
        recordReq.setStuId(stuId);
        recordReq.setPlanId(planId);
        recordReq.setType(RX_REGISTRATION_CHARGE_PAYMENT_RECORD_TYPE_WELCOME);
        recordReq.setOpenId(req.getOpenId());
        recordReq.setWxPayFunction(wxPayFunction);
        recordReq.setMode(RX_REGISTRATION_CHARGE_PAYMENT_RECORD_MODE_ONLINE);
        recordReq.setDivideReqList(divideReqList);
        RxRegistrationPrepayPaymentResp prepayPaymentResp = paymentUtil.payment(recordReq);
        if (prepayPaymentResp == null) {
            return CommonResult.failed(CommonCodeEnum.RX_REGISTRATION_ADVANCE_PAYMENT_FAIL);
        }

        return CommonResult.success(prepayPaymentResp);
    }



    /**
     * @description 收费项处理  校验并输出收费项集合
     * @create 2024/5/21
     * @author dxn
     */
    private List<RxRegistrationChargePaymentCategoryDivideReq> chargeCategoryOperation(String stu_id,
                                                                                       List<RxRegistrationChargeCategoryRecordReq> chargeCategoryRecordList) {
        List<RxRegistrationChargePaymentCategoryDivideReq> divideList = new ArrayList<>();

        RxRegistrationAdvanceStudentInfo studentInfo = rxRegistrationAdvanceStudentInfoMapper.selectById(stu_id);

        //获取收费项设置列表
        RxRegistrationAdvanceStudentInfoResp welcomeAllStuPaymentCategory = welcomeStuUtil.getWelcomeAllStuPaymentCategory(studentInfo);
        List<RxRegistrationPlanChargeCategoryResp> pendingChargeCategoryList = welcomeAllStuPaymentCategory.getChargeCategoryRespList();

        for (RxRegistrationPlanChargeCategoryResp pendingChargeCategory : pendingChargeCategoryList) {
            //匹配与系统收费项集合进行匹配
            List<RxRegistrationChargeCategoryRecordReq> filterList = chargeCategoryRecordList
                    .stream()
                    .filter(record -> record.getMainId().equals(pendingChargeCategory.getChargeCategoryId()))
                    .collect(Collectors.toList());
            //判断是否必填
            if (pendingChargeCategory.getIsRequired()) {
                //必填 且未填写 报错
                if (filterList.size() < 1) {
                    ExceptionCast.cast(CommonResult.failed(CommonCodeEnum.RX_REGISTRATION_CONFIRM_CHARGE_CATEGORY_REQUIRED_NOT_FILL));
                }
            }

            //不必填 且未填写 跳过
            if (filterList.size() < 1) {
                continue;
            }

            //校验已填写单选 多选
            RxRegistrationChargeCategoryRecordReq filterRecord = filterList.get(0);
            if (pendingChargeCategory.getChargeCategoryType() == CHARGE_CATEGORY_TYPE_MAJOR) {
                if (filterRecord.getChildList().size() != 1) {
                    ExceptionCast.cast(CommonResult.failed(CommonCodeEnum.RX_REGISTRATION_CONFIRM_CHARGE_CATEGORY_REQUIRED_FILL_ERROR));
                }

                String childId = filterRecord.getChildList().get(0).getChildId();
                addChargeCategoryToList(divideList, pendingChargeCategory, childId);
            }else if (pendingChargeCategory.getChargeCategoryType() == CHARGE_CATEGORY_TYPE_SIGNAL) {
                if (filterRecord.getChildList().size() != 1) {
                    ExceptionCast.cast(CommonResult.failed(CommonCodeEnum.RX_REGISTRATION_CONFIRM_CHARGE_CATEGORY_REQUIRED_FILL_ERROR));
                }

                String childId = filterRecord.getChildList().get(0).getChildId();
                addChargeCategoryToList(divideList, pendingChargeCategory, childId);
            } else if (pendingChargeCategory.getChargeCategoryType() == CHARGE_CATEGORY_TYPE_MULTIPLE) {
                if (filterRecord.getChildList().size() > pendingChargeCategory.getChildList().size()
                        || filterRecord.getChildList().size() < 1) {
                    ExceptionCast.cast(CommonResult.failed(CommonCodeEnum.RX_REGISTRATION_CONFIRM_CHARGE_CATEGORY_REQUIRED_FILL_ERROR));
                }

                for (RxRegistrationChargeCategoryRecordDetailReq childRecord : filterRecord.getChildList()) {
                    String childId = childRecord.getChildId();
                    addChargeCategoryToList(divideList, pendingChargeCategory, childId);
                }
            } else {
                addChargeCategoryToList(divideList, pendingChargeCategory, null);
            }
        }

        //删除缴费项记录
        if (studentInfo.getAdvanceStatus() != REGISTRATION_STATUS_FINISH
                || studentInfo.getConfirmStatus() != REGISTRATION_STATUS_FINISH
                || studentInfo.getWelcomeStatus() != REGISTRATION_STATUS_FINISH) {
            LambdaQueryWrapper<RxRegistrationChargeCategoryRecord> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(RxRegistrationChargeCategoryRecord::getStuId, stu_id)
                    .and(wrapper -> {
                        if (studentInfo.getAdvanceStatus() != REGISTRATION_STATUS_FINISH) {
                            wrapper.eq(RxRegistrationChargeCategoryRecord::getAppType, APP_TYPE_ADVANCE);
                        }
                        if (studentInfo.getConfirmStatus() != REGISTRATION_STATUS_FINISH) {
                            wrapper.or().eq(RxRegistrationChargeCategoryRecord::getAppType, APP_TYPE_CONFIRM);
                        }
                        if (studentInfo.getWelcomeStatus() != REGISTRATION_STATUS_FINISH) {
                            wrapper.or().eq(RxRegistrationChargeCategoryRecord::getAppType, APP_TYPE_WELCOME);
                        }
                    });
            rxRegistrationChargeCategoryRecordMapper.delete(queryWrapper);
        }
        //保存记录
        List<RxRegistrationChargeCategoryRecord> recordList = divideList.stream()
                .map(divide -> {
                    RxRegistrationChargeCategoryRecord record = new RxRegistrationChargeCategoryRecord();
                    record.setStuId(stu_id);
                    record.setAppType(APP_TYPE_WELCOME);
                    record.setMainId(divide.getCategoryId());
                    record.setMainName(divide.getCategoryName());
//                    record.setMainType(pendingChargeCategoryList.stream()
//                            .filter(pendingChargeCategory -> pendingChargeCategory.getChargeCategoryId().equals(divide.getCategoryId())));
                    record.setPrice(divide.getAmount());
                    record.setChildId(divide.getCategoryDetailId());
                    record.setChildName(divide.getCategoryDetailName());
                    return record;
                })
                .collect(Collectors.toList());
        rxRegistrationChargeCategoryRecordService.saveBatch(recordList);
        return divideList;
    }


    private List<RxRegistrationChargeCategoryRecordResp> getChargeCategoryRecordList(RxRegistrationAdvanceStudentInfo studentInfo) {
        List<RxRegistrationChargeCategoryRecordResp> chargeCategoryRecordRespList = new ArrayList<>();
        LambdaQueryWrapper<RxRegistrationChargeCategoryRecord> queryWrapper = new LambdaQueryWrapper<>();
        if (studentInfo == null) {
            return chargeCategoryRecordRespList;
        }
        queryWrapper.eq(RxRegistrationChargeCategoryRecord::getStuId, studentInfo.getId())
                .orderByAsc(RxRegistrationChargeCategoryRecord::getAppType);
        if (studentInfo.getAdvanceStatus() == REGISTRATION_STATUS_FINISH
                || studentInfo.getConfirmStatus() == REGISTRATION_STATUS_FINISH
                || studentInfo.getWelcomeStatus() == REGISTRATION_STATUS_FINISH) {
            queryWrapper.and(wrapper -> {
                if (studentInfo.getAdvanceStatus() == REGISTRATION_STATUS_FINISH) {
                    wrapper.eq(RxRegistrationChargeCategoryRecord::getAppType, APP_TYPE_ADVANCE);
                }
                if (studentInfo.getConfirmStatus() == REGISTRATION_STATUS_FINISH) {
                    wrapper.or()
                            .eq(RxRegistrationChargeCategoryRecord::getAppType, APP_TYPE_CONFIRM);
                }
                if (studentInfo.getWelcomeStatus() == REGISTRATION_STATUS_FINISH) {
                    wrapper.or()
                            .eq(RxRegistrationChargeCategoryRecord::getAppType, APP_TYPE_WELCOME);
                }
            });
        }else{
            return chargeCategoryRecordRespList;
        }

        chargeCategoryRecordRespList = rxRegistrationChargeCategoryRecordMapper.selectList(queryWrapper)
                .stream()
                .map(record -> {
                    RxRegistrationChargeCategoryRecordResp chargeCategoryResp = new RxRegistrationChargeCategoryRecordResp();
                    BeanUtils.copyProperties(record, chargeCategoryResp);
                    return chargeCategoryResp;
                })
                .collect(Collectors.toList());
        return chargeCategoryRecordRespList;
    }

    private void addChargeCategoryToList(List<RxRegistrationChargePaymentCategoryDivideReq> divideList,
                                         RxRegistrationPlanChargeCategoryResp pendingChargeCategory,
                                         String childId) {
        RxRegistrationChargePaymentCategoryDivideReq divideReq = new RxRegistrationChargePaymentCategoryDivideReq();
        divideReq.setCategoryId(pendingChargeCategory.getChargeCategoryId());
        divideReq.setCategoryName(pendingChargeCategory.getChargeCategoryName());
        if (!isNullOrEmpty(childId)) {
            List<RxRegistrationChargeCategoryDetailResp> childFilterRecordList = pendingChargeCategory.getChildList()
                    .stream()
                    .filter(child -> child.getChargeCategoryId().equals(childId))
                    .collect(Collectors.toList());
            if (childFilterRecordList.size() < 1) {
                ExceptionCast.cast(CommonResult.failed(CommonCodeEnum.RX_REGISTRATION_CONFIRM_CHARGE_CATEGORY_CHILD_ERROR));
            }
            divideReq.setCategoryDetailId(childFilterRecordList.get(0).getChargeCategoryId());
            divideReq.setCategoryDetailName(childFilterRecordList.get(0).getChargeCategoryName());
            divideReq.setAmount(childFilterRecordList.get(0).getChargeCategoryPrice());
        } else {
            divideReq.setAmount(pendingChargeCategory.getChargeCategoryPrice());
        }
        divideList.add(divideReq);
    }
    @Override
    @Transactional
    public ResponseResult addStuInfo(RxRegistrationAdvanceStudentInfoAddReq addReq) {
        checkRequiredInfo(addReq);
        //校验计划
        String planId = addReq.getPlanId();
        //查询计划是否存在并启用
        List<RxRegistrationPlanSetting> planSettingList = rxRegistrationPlanSettingMapper.selectList(new LambdaQueryWrapper<RxRegistrationPlanSetting>()
                .eq(RxRegistrationPlanSetting::getId, planId)
                .eq(RxRegistrationPlanSetting::getPlanStatus, PLAN_STATUS_ENABLE));
        if (planSettingList.isEmpty()) {
            ExceptionCast.cast(CommonResult.failed(CommonCodeEnum.RX_REGISTRATION_ADVANCE_PLAN_NOT_EXIST));
        }
        String planName = planSettingList.get(0).getPlanName();
        //校验组织
        String orgName = null;
        if (!isNullOrEmpty(addReq.getOrgId())) {
            RxAdvanceRegistrationOrg advanceRegistrationOrg = rxAdvanceRegistrationOrgMapper.selectById(addReq.getOrgId());
            if (isNullOrEmpty(advanceRegistrationOrg)) {
                ExceptionCast.cast(CommonResult.failed(CommonCodeEnum.ADVANCE_REGISTRATION_ORG_NOT_EXIST));
            }
            orgName = advanceRegistrationOrg.getMajorName();
        }
        //创建学生信息
        RxRegistrationAdvanceStudentInfo rxRegistrationAdvanceStudentInfo = new RxRegistrationAdvanceStudentInfo();
        BeanUtils.copyProperties(addReq, rxRegistrationAdvanceStudentInfo);
        rxRegistrationAdvanceStudentInfo.setPlanName(planName);
        rxRegistrationAdvanceStudentInfo.setOrgName(orgName);
        rxRegistrationAdvanceStudentInfo.setAdvanceStatus(REGISTRATION_STATUS_GOING_ON);
        rxRegistrationAdvanceStudentInfoMapper.insert(rxRegistrationAdvanceStudentInfo);

        String stuId = rxRegistrationAdvanceStudentInfo.getId();
        if (isNullOrEmpty(stuId)) {
            return CommonResult.failed(CommonCodeEnum.FAIL);
        }
        //自定义必填字段
        List<RxRegistrationAdvanceCustomColumnValueReq> customColumnValueList = addReq.getCustomColumnValueList();//传入的自定义字段
        //创建该学生自定义信息
        if (customColumnValueList != null && customColumnValueList.size() > 0) {
            for (RxRegistrationAdvanceCustomColumnValueReq rxRegistrationAdvanceCustomColumnValueReq : customColumnValueList) {
                RxRegistrationCustomColumnValue rxRegistrationAdvanceCustomColumnValue = new RxRegistrationCustomColumnValue();
                BeanUtils.copyProperties(rxRegistrationAdvanceCustomColumnValueReq, rxRegistrationAdvanceCustomColumnValue);
                rxRegistrationAdvanceCustomColumnValue.setStudentId(stuId);
                rxRegistrationAdvanceCustomColumnValue.setPlanId(planId);
                rxRegistrationCustomColumnValueMapper.insert(rxRegistrationAdvanceCustomColumnValue);
            }
        }

        return CommonResult.success();
    }


    /**
     * 检验必要信息
     * @param req 学校信息 自定义字段 收费项
     */
    private void checkRequiredInfo(RxRegistrationAdvanceStudentInfoAddReq req) {
        //参数校验
        if (isNullOrEmpty(req.getPlanId(),req.getName(),req.getMiddleSchool(),req.getMiddleSchoolId(),req.getMiddleSchoolClasses(),
                req.getIdCard(),req.getTel())) {
            ExceptionCast.cast(CommonResult.failed(CommonCodeEnum.INVALID_PARAM));
        }
        //校验计划
        String planId = req.getPlanId();
        //校验提交预报名是否在计划有效期内
        List<RxRegistrationPlanAppSetting> appSettingList = rxRegistrationPlanAppSettingMapper.selectList(new LambdaQueryWrapper<RxRegistrationPlanAppSetting>()
                .eq(RxRegistrationPlanAppSetting::getPlanId, planId)
                .eq(RxRegistrationPlanAppSetting::getAppType, APP_TYPE_ADVANCE));
        if (appSettingList.isEmpty()) {
            ExceptionCast.cast(CommonResult.failed(CommonCodeEnum.RX_REGISTRATION_ADVANCE_PLAN_NOT_EXIST));
        }
        //获取招生计划下阶段招生开放时间
        Date nowDate = new Date();
        List<RxRegistrationPlanAppSetting> planAppSettingList = rxRegistrationPlanAppSettingMapper.selectList(new LambdaQueryWrapper<RxRegistrationPlanAppSetting>()
                .eq(RxRegistrationPlanAppSetting::getPlanId, planId)
                .lt(RxRegistrationPlanAppSetting::getBgTime, nowDate) //开始时间小于当前时间
                .gt(RxRegistrationPlanAppSetting::getEndTime, nowDate)  //结束时间大于当前时间
                .orderByDesc(RxRegistrationPlanAppSetting::getAppType));
        if (planAppSettingList == null || planAppSettingList.size() == 0) {
            ExceptionCast.cast(CommonResult.failed(CommonCodeEnum.RX_REGISTRATION_ADVANCE_NOT_SUBMIT));
        }

        //校验身份证和电话
        boolean validIDCard = ParamCheckUtil.isValidIDCard(req.getIdCard());
        if (!validIDCard) {
            ExceptionCast.cast(CommonResult.failed(CommonCodeEnum.ENROLLMENT_MANAGEMENT_STUDENT_ID_CARD_ERR));
        }
        boolean validPhone = ParamCheckUtil.isValidPhone(req.getTel());
        if (!validPhone) {
            ExceptionCast.cast(CommonResult.failed(CommonCodeEnum.ADVANCE_REGISTRATION_TEL_ERR));
        }
        //校验自定义必填字段
        List<RxRegistrationAdvanceCustomColumnValueReq> customColumnValueList = req.getCustomColumnValueList();//传入的自定义字段
        List<RxRegistrationCustomColumn> customColumnList = rxRegistrationCustomColumnMapper.selectList(new LambdaQueryWrapper<RxRegistrationCustomColumn>()
                .in(RxRegistrationCustomColumn::getAppType, appTypeList)
                .eq(RxRegistrationCustomColumn::getPlanId, planId));//设置的自定义字段
        //设置了自定义字段
        if (customColumnList != null && customColumnList.size() > 0) {
            if (customColumnList.size() != customColumnValueList.size()) {
                ExceptionCast.cast(CommonResult.failed(CommonCodeEnum.INVALID_PARAM));
            }
            //自定义字段为
            for (RxRegistrationAdvanceCustomColumnValueReq rxRegistrationAdvanceCustomColumnValueReq : customColumnValueList) {
                if (rxRegistrationAdvanceCustomColumnValueReq.getIsRequired()) {
                    if (isNullOrEmpty(rxRegistrationAdvanceCustomColumnValueReq.getColumnValue(),rxRegistrationAdvanceCustomColumnValueReq.getColumnId())) {
                        ExceptionCast.cast(CommonResult.failed(CommonCodeEnum.ADVANCE_REGISTRATION_CUSTOM_COLUMN_NOT_SET));
                    }
                }
            }
        }


}


}
